package com.hdax.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class MainApplication {
    public static void main(String[] args) {
        //SecurityManager shiro核心对象
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        SecurityUtils.setSecurityManager(securityManager);

        String username = "admin";
        String password = "123456";

        //令牌 token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        //执行登录：认证
        Subject subject = SecurityUtils.getSubject();

        try{
            subject.login(token);
            System.out.println("登录成功！");
            //授权校验
            //是否拥有role1
            System.out.println("是否拥有role1:"+subject.hasRole("role1"));//true
            System.out.println("是否拥有role3:"+subject.hasRole("role3"));//false

            //是否拥有权限
            System.out.println("能不能添加应用："+subject.isPermitted("app:insert"));// true   app:*
            System.out.println("能不能修改应用："+subject.isPermitted("app:update"));//true

        } catch (UnknownAccountException e){
            System.out.println("用户名不存在");
        } catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
        }

    }
}
